# -*- coding: utf-8 -*-

import urllib
import re
import json
import sys

from base import mcMovie
from base import mcSource
from base import mcSubtitle
from base import mcAudio
from base import mcDown
from base import mcScrapper
from base import mcLang

class cuevanaMovie(mcMovie):

	def __init__ (self, id=None):
		mcMovie.__init__(self, "cuevana", id)

	def loadInfo(self):

		self.url = "http://www.cuevana.tv/web/peliculas?&" + self.id + "&"
		
		salida = self._mcData.get( self.url )
		salida = salida.replace('\n', ' ')
		#print salida

		#Cover
		rec_cover_url = re.compile('"img"><img src="([^"]*)')
		match = re.search(rec_cover_url, salida )
		if match != None:
			self.cover_url = match.group(1)

		#Title
		rec_title = re.compile('"tit">([^<]*)')
		match = re.search(rec_title, salida )
		if match != None:
			self.title = unicode(match.group(1).strip(), 'utf-8')


		#Original Title
		rec_original_title = re.compile('tulo original</h2>([^<]*)')
		match = re.search(rec_original_title, salida )
		if match != None:
			self.original_title = unicode(match.group(1).strip(), 'utf-8')


		self.url = "http://www.cuevana.tv/#!/peliculas/"+ self.id +"/"

		#Parent Call
		mcMovie.loadInfo(self)


	def loadSources(self):		
		
		
		
		self.sources = []
		
		url = "http://www.cuevana.tv/player/sources?id="+self.id+"&tipo=pelicula"
		salida = self._mcData.get( url )
		#salida = salida.replace('\n', ' ')
		#print salida

		str1 = "var sources ="
		pos = salida.find(str1)
		pos2 = salida.find("var label =")

		strjson = salida[pos+len(str1):pos2-len(", sel_source = 0; ")]
		result = json.loads(strjson)
		#print result
		for definition in result:
			for lang in result[definition]:
				for server in result[definition][lang]:
					#print server
					s = mcSource()
					s.service = self.service
					s.id = self.id
					s.server = server
					s.definition = definition
					if int(definition) >= 720:
						s.is_hd = True
					
					s.audio_lang_id = lang
					s.audio_lang = self._getLangFromId(lang)
					
					#self._loadSourceUrl(s)
				
					self.sources.append(s)

		#Parent Call
		mcMovie.loadSources(self)



	def _loadSourceUrl(self, source):

		url = "http://www.cuevana.tv/player/source_get"

		data = {'def': source.definition,
			#'audio': source.audio_lang_id,
			'audio': source.audio_lang,
			'host': source.server,
			'id': self.id,
			'tipo': 'pelicula',
			'wup_premium' : 'false'
			}

		post = urllib.urlencode(data)

		salida = self._mcData.post(url, post)
		
		pos = salida.find('id="captcha"')
		
		if pos > 0:			
			#Captcha
			base_url = url + "?" + post
			
			result=""
			while True:			
				#Recaptcha here				
				print "Getting " + source.server + " ... " 
				
				post = mcDown.reCaptcha('6LeO_MwSAAAAABVHhC7ftszdwEtjTpe-gId7KshJ', 'sources_cookies')
				
				headers =  { 'X-Requested-With': 'XMLHttpRequest', 'Referer': base_url, 'Content-Type' : 'application/x-www-form-urlencoded' }
				out = mcScrapper.request(base_url, post, None, headers)
					
				result = out['srt']
				
				#result = self.reCaptcha('6LeO_MwSAAAAABVHhC7ftszdwEtjTpe-gId7KshJ', base_url , 'sources_cookies')				
				if result.find('id="captcha"') < 0:
					print "Salir"
					
					rec_surl = re.compile("http://go.cuevana.tv/\?([^']*)")
					match = re.search(rec_surl, result )
					if match != None:					
						result = urllib.unquote_plus( match.group(1) )
					
					if  source.server == 'wupload':
						result = out['url']
					
					break
				
				print "Recaptcha Again"			
			
			source.url = result
			print source.url
			
		else:	
			salida = salida.strip().replace('\xef\xbb\xbf', '')
			if source.server == 'megaupload':
				pos = salida.find('&id='+ self.id)
				salida = salida[:pos]

			if source.server == 'wupload':
				pos = salida.find('?id='+ self.id)
				salida = salida[:pos]

			source.url = salida
		


	

	




	def loadSubtitles(self):
		
		self.subtitles = []

		url = "http://www.cuevana.tv/web/peliculas?&" + str( self.id ) + "&"
		
		salida = self._mcData.get( url )
		salida = salida.replace('\n', ' ')
		
		#Idiomas
		rec_sublang = re.compile('tulos:</b>([^<]*)')
		match = re.search(rec_sublang, salida )
		if match != None:
			
			langs = []
			
			code = match.group(1).strip()			
			code = mcLang.getCodeFromName_ES( code )

			#Split here			
			for i in self.sources:						
				s = mcSubtitle()
				s.service = self.service
				s.id = self.id
				s.server = i.server
				s.definition = i.definition
				s.audio_lang = i.audio_lang				
				s.lang = code
				
				if s.definition == "720":
					s.url = "http://sc.cuevana.tv/files/sub/"+s.id+"_"+s.lang+"_"+s.definition+".srt"
				else:
					s.url = "http://sc.cuevana.tv/files/sub/"+s.id+"_"+s.lang+".srt"				
				
				langs.append( s )
			
			self.subtitles = langs

		#Parent Call
		mcMovie.loadSubtitles(self)

	def loadAudios(self):
		
		self.audios = []

		url = "http://www.cuevana.tv/web/peliculas?&" + str( self.id ) + "&"
		
		salida = self._mcData.get( url )
		salida = salida.replace('\n', ' ')

		rec_lang = re.compile('<b>Idioma:</b>([^<]*)')
		match = re.search(rec_lang, salida )
		if match != None:
			langs = []

			code = match.group(1).strip()			
			code = mcLang.getCodeFromName_ES( code )

			s = mcAudio()
			s.service = self.service
			s.id = self.id
			s.lang = code
			langs.append( s )

			self.audios = langs

		#Parent Call
		mcMovie.loadAudios(self)


	def downSource(self, source):	
		loaded = self.dbExistSource(source)
		if not loaded:
			self._loadSourceUrl(source)
			self.dbStoreSource(source)
			#TODO: validate link exists first
		else:
			source.url = loaded
		
		#Parent Call
		mcMovie.downSource(self, source)		
		
	def downSubtitle(self, lang_code):		
		#Parent Call
		mcMovie.downSubtitle(self)	

	langs_list = json.loads('{"1":"Espa\u00f1ol","2":"Ingl\u00e9s","3":"Portugu\u00e9s","4":"Alem\u00e1n","5":"Franc\u00e9s","6":"Coreano","7":"Italiano","8":"Tailand\u00e9s","9":"Ruso","10":"Mongol","11":"Polaco","12":"Esloveno","13":"Sueco","14":"Griego","15":"Canton\u00e9s","16":"Japon\u00e9s","17":"Dan\u00e9s","18":"Neerland\u00e9s","19":"Hebreo","20":"Serbio","21":"\u00c1rabe","22":"Hindi","23":"Noruego","24":"Turco","26":"Mandar\u00edn","27":"Nepal\u00e9s","28":"Rumano","29":"Iran\u00ed","30":"Est\u00f3n","31":"Bosnio","32":"Checo","33":"Croata","34":"Fin\u00e9s","35":"H\u00fanagro"}' )	
	def _getLangFromId(self, id):
		name = self.langs_list[ str(id) ].encode('utf8')
		return mcLang.getCodeFromName_ES( name )
	
	def _getIdFromName(self, name):		
		for i in self.langs_list:
			if self.langs_list[i].encode('utf8') == name:
				return i
		return 0

	@staticmethod
	def featured():

		o = cuevanaMovie()

		url = "http://www.cuevana.tv/web/inicio"

		salida = o._mcData.get( url )

		search1 = '$("#peliculas_row").rowbox('
		pos = salida.find(search1)
		salida2 = salida[pos + len(search1) + 2 :]

		search2 = '$("#episodios_row").rowbox('
		pos = salida2.find(search2)

		finish = ",set:['tit','ano','reparto','director','genero','idioma','duracion']}"
		peliculas = '{"lista"' + salida2[:pos-3-len(finish)] + "}"

		#peliculas = open('info.txt').read()
		#print peliculas
		import json
		peliculas = unicode(peliculas, 'latin-1')
		peliculas = json.loads(peliculas)
		
		result = []
		#for pel in peliculas['lista']['destacado']:
		for pel in peliculas['lista']['estreno']:			

			"""
			o = mcMovie()
			o.id = unicode(pel['id']).encode("utf-8")
			o.title = unicode(pel['tit']).encode("utf-8")
			"""
			o = cuevanaMovie( unicode(pel['id']).encode("utf-8") )
			result.append(o)

		return result






class cuevanaSerie(cuevanaMovie):
	def __init__ (self, id=None):
		mcMovie.__init__(self, "cuevana_serie", id)


	def getEpisodes(self, numero):
		
		self.url = "http://www.cuevana.tv/web/series?&" + str(self.id) + "&"
		
		salida = self._mcData.get( self.url )
		salida = salida.replace('\n', ' ')


		s1 = "$('#temporadas').serieList({l:"		
		p1 = salida.find(s1) + len(s1)

		s2 = ",e:$('#episodios')});"
		p2 = salida.find(s2)
		
		sj = salida[p1:p2]

		temporadas = json.loads(sj)		
		
		c=0
		for i in temporadas:
			c=c+1
			
		if numero > c:
			return []
		if numero < 0:
			return []
		
		temp = temporadas[str(numero)]

		episodes = []
		for j in temp:
			id = "http://www.cuevana.tv/" + j['url']			
			e = cuevanaEpisode( id)
			episodes.append( e )
		
		return episodes



	def loadInfo(self):
		
		self.url = "http://www.cuevana.tv/web/series?&" + str(self.id) + "&"
		
		salida = self._mcData.get( self.url )
		salida = salida.replace('\n', ' ')

		#Cover
		rec_cover_url = re.compile('"img"><img src="([^"]*)')
		match = re.search(rec_cover_url, salida )
		if match != None:
			self.cover_url = match.group(1)

		#Title
		rec_title = re.compile('"tit">([^<]*)')
		match = re.search(rec_title, salida )
		if match != None:
			self.title = unicode(match.group(1).strip(), 'utf-8')


		#Original Title
		rec_original_title = re.compile('tulo original</h2>([^<]*)')
		match = re.search(rec_original_title, salida )
		if match != None:
			self.original_title = unicode(match.group(1).strip(), 'utf-8')


		self.url = "http://www.cuevana.tv/#!/peliculas/"+ str(self.id) +"/"

		#Parent Call
		mcMovie.loadInfo(self)		


	def loadSources(self):		
		
		pass

class cuevanaEpisode(cuevanaMovie):
	def __init__ (self, id=None):
		mcMovie.__init__(self, "cuevana_episode", id)

	def loadInfo(self):
		
		#id is a url like http://www.cuevana.tv/#!/series/12098/psych/shawn-rescues-darth-vader
		
		real_id=""
		serie=""
		episode=""		
		rec_url = re.compile('#!/series/([^/]*)/([^/]*)/([^/]*)')
		match = re.search(rec_url, self.id )
		if match != None:
			real_id = match.group(1)
			serie    = match.group(2)
			episode	 = match.group(3)			
		
		self.url = "http://www.cuevana.tv/web/series?&" + real_id + "&" + serie +"&" + episode

		salida = self._mcData.get( self.url )
		salida = salida.replace('\n', ' ')

		#Serie
		rec_cover_url = re.compile('#!/series/([^"]*)')
		match = re.search(rec_cover_url, salida )
		if match != None:
			self.original_title = "http://www.cuevana.tv/#!/series/" + match.group(1)


		#Cover
		rec_cover_url = re.compile('"img"><img src="([^"]*)')
		match = re.search(rec_cover_url, salida )
		if match != None:
			self.cover_url = match.group(1)

		#Title
		rec_title = re.compile('"tit">([^<]*)')
		match = re.search(rec_title, salida )
		if match != None:
			self.title = unicode(match.group(1).strip(), 'utf-8')


		#~ #Original Title
		#~ rec_original_title = re.compile('tulo original</h2>([^<]*)')
		#~ match = re.search(rec_original_title, salida )
		#~ if match != None:
			#~ self.original_title = unicode(match.group(1).strip(), 'utf-8')

		#Parent Call
		mcMovie.loadInfo(self)


	def loadSources(self):		
		
		self.sources = []

		real_id=""
		rec_url = re.compile('#!/series/([^/]*)/([^/]*)/([^/]*)')
		match = re.search(rec_url, self.id )
		if match != None:
			real_id = match.group(1)
		
		url = "http://www.cuevana.tv/player/sources?id="+real_id+"&tipo=serie"
		salida = self._mcData.get( url )
		#salida = salida.replace('\n', ' ')
		#print salida

		str1 = "var sources ="
		pos = salida.find(str1)
		pos2 = salida.find("var label =")

		strjson = salida[pos+len(str1):pos2-len(", sel_source = 0; ")]
		result = json.loads(strjson)
		#print result
		for definition in result:
			for lang in result[definition]:
				for server in result[definition][lang]:
					#print server
					s = mcSource()
					s.service = self.service
					s.id = self.id
					s.server = server
					s.definition = definition
					if int(definition) >= 720:
						s.is_hd = True
					
					s.audio_lang_id = lang
					s.audio_lang = self._getLangFromId(lang)
					
					#self._loadSourceUrl(s)
				
					self.sources.append(s)

		#Parent Call
		mcMovie.loadSources(self)

	def _loadSourceUrl(self, source):

		url = "http://www.cuevana.tv/player/source_get"

		real_id=""
		rec_url = re.compile('#!/series/([^/]*)/([^/]*)/([^/]*)')
		match = re.search(rec_url, self.id )
		if match != None:
			real_id = match.group(1)

		lang_names =mcLang.getName_ESFromCode(	source.audio_lang )
		audio_lang_id = self._getIdFromName(lang_names)

		data = {'def': source.definition,
			'audio': audio_lang_id,
			'host': source.server,
			'id': real_id,
			'tipo': 'serie',
			'wup_premium' : 'false'
			}

		post = urllib.urlencode(data)

		print url + post
		
		salida = self._mcData.post(url, post)
		
		pos = salida.find('id="captcha"')
		
		if pos > 0:			
			#Captcha
			base_url = url + "?" + post
			
			result=""
			while True:			
				#Recaptcha here				
				print "Getting " + source.server + " ... " 
				
				post = mcDown.reCaptcha('6LeO_MwSAAAAABVHhC7ftszdwEtjTpe-gId7KshJ', 'sources_cookies')
				
				headers =  { 'X-Requested-With': 'XMLHttpRequest', 'Referer': base_url, 'Content-Type' : 'application/x-www-form-urlencoded' }
				out = mcScrapper.request(base_url, post, None, headers)
					
				result = out['srt']
				
				print result
				
				#result = self.reCaptcha('6LeO_MwSAAAAABVHhC7ftszdwEtjTpe-gId7KshJ', base_url , 'sources_cookies')				
				if result.find('id="captcha"') < 0:
					print "Salir"
					
					rec_surl = re.compile("http://go.cuevana.tv/\?([^']*)")
					match = re.search(rec_surl, result )
					if match != None:					
						result = urllib.unquote_plus( match.group(1) )
					
					if  source.server == 'wupload':
						result = out['url']
					
					break
				
				print "Recaptcha Again"			
			
			source.url = result
			print source.url
			
		else:	
			salida = salida.strip().replace('\xef\xbb\xbf', '')
			if source.server == 'megaupload':
				pos = salida.find('&id='+ self.id)
				salida = salida[:pos]

			if source.server == 'wupload':
				pos = salida.find('?id='+ self.id)
				salida = salida[:pos]

			source.url = salida

	def loadSubtitles(self):
		
		self.subtitles = []

		real_id=""
		rec_url = re.compile('#!/series/([^/]*)/([^/]*)/([^/]*)')
		match = re.search(rec_url, self.id )
		if match != None:
			real_id = match.group(1)

		url = "http://www.cuevana.tv/web/series?&" + str( real_id ) + "&"
		
		salida = self._mcData.get( url )
		salida = salida.replace('\n', ' ')
		
		#Idiomas
		rec_sublang = re.compile('tulos:</b>([^<]*)')
		match = re.search(rec_sublang, salida )
		if match != None:
			
			langs = []
			
			code = match.group(1).strip()			
			code = mcLang.getCodeFromName_ES( code )

			#Split here			
			for i in self.sources:						
				s = mcSubtitle()
				s.service = self.service
				s.id = self.id
				s.server = i.server
				s.definition = i.definition
				s.audio_lang = i.audio_lang				
				s.lang = code
				
				if s.definition == "720":
					s.url = "http://sc.cuevana.tv/files/s/sub/"+s.id+"_"+s.lang+"_"+s.definition+".srt"
				else:
					s.url = "http://sc.cuevana.tv/files/s/sub/"+s.id+"_"+s.lang+".srt"				
				
				langs.append( s )
			
			self.subtitles = langs

		#Parent Call
		mcMovie.loadSubtitles(self)
		
#http://sc.cuevana.tv/files/s/sub/12098_ES.srt